Database   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 65
dl 0
loc 89
rs 10
c 0
b 0
f 0
wmc 13

10 Functions

Rating   Name   Duplication   Size   Complexity  
A showTables 0 3 1
A setIndexes 0 4 1
A allModels 0 3 1
A query 0 26 4
A table 0 3 1
A drop 0 3 1
A ids 0 3 1
A addIndex 0 3 1
A indexes 0 3 1
A register 0 4 1
1
import {ModelInterface, ModelStaticInterface} from "../JeloquentInterfaces";
2
import Table from "./Table";
3
4
export default class Database {
5
6
    private _name: string;
7
8
    private _tables: Map<string, Table>;
9
10
    /**
11
     *
12
     * @param name
13
     * @param models
14
     */
15
    constructor(name, models:Array<ModelStaticInterface>) {
16
        this._name = name;
17
        this._tables = new Map();
18
19
        models.forEach((model: ModelStaticInterface) => {
20
            this.register(model);
21
        });
22
    }
23
24
    get name(): string {
25
        return this._name;
26
    }
27
28
    addIndex(table:string, indexName:string, lookUpKey:string, id:string|number): void {
29
        this.table(table).addIndex(indexName, lookUpKey, id)
30
    }
31
32
    allModels(table): Map<string|number, ModelInterface> {
33
        return this.table(table).allModels();
34
    }
35
36
    drop(table: string): void {
37
        this._tables.delete(table);
38
    }
39
40
    ids(table: string): Array<string|number> {
41
        return this.table(table).ids;
42
    }
43
44
    indexes(table: string): Map<string, Map<string|number, Set<string|number>>>  {
45
        return this.table(table).indexes;
46
    }
47
48
    /**
49
     * @todo Build better way of parsing queries;
50
     */
51
    query(sql) {
52
        const sqlParts = sql.match(/^((SELECT)|(INSERT)|(DELETE))\s+(.*)\s+FROM\s+([^\s]+)(\s+WHERE\s+([^\s]+)\s+(=)\s+([^\s+]))?((\s+)|;)?$/i);
53
54
        if (sqlParts.length === 0) {
55
            return null;
56
        }
57
58
        const action = sqlParts[1];
59
        //const fields = sqlParts[5].split(',');
60
        const table = sqlParts[6]
61
        const matchField = sqlParts[8];
62
        const matchValue = sqlParts[10];
63
64
        if (matchField === 'id') {
65
            return this.table(table)[action.toLowerCase()](matchValue);
66
        }
67
68
        if (matchField === undefined && action === 'SELECT') {
69
            return this.table(table).all();
70
        }
71
72
        return null;
73
    }
74
75
    register(model: ModelStaticInterface) {
76
        const table = new Table(model);
77
        this._tables.set(table.name, table);
78
    }
79
80
    setIndexes(): void {
81
        this._tables.forEach((table) => {
82
            table.setupIndexes();
83
        });
84
    }
85
86
    showTables(): Array<string> {
87
        return [...this._tables.keys()];
88
    }
89
90
    table(name:string): Table {
91
        return this._tables.get(name);
92
    }
93
}